package com.xywl.escort.view.order.purchase

import android.graphics.Paint
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.PurchaseOrderDetailAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.LogisticsResp
import com.xywl.escort.bean.PurchaseOrderDetailBean
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.CustomDialog
import com.xywl.escort.widget.CustomDialog2
import com.xywl.escort.widget.HorizontalDividerItemDecoration
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_purchase_order_detail.*
import kotlinx.android.synthetic.main.view_order_footer.view.*
import kotlinx.android.synthetic.main.view_order_header.view.*
import timber.log.Timber
import java.math.BigDecimal
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

/**
 * 采购订单详情
 */
@Route(path = "/xy/order/purchase/detail")
class PurchaseOrderDetailActivity : BaseActivity(), PurchaseOrderDetailContract.View {
    private lateinit var mAdapter: PurchaseOrderDetailAdapter
    private var countdown: Countdown? = null

    @Autowired
    @JvmField
    var orderId: String = ""

    private var headerView: View? = null
    private var footerView: View? = null
    private var couponId: String? = ""

    @Inject
    lateinit var mPresenter: PurchaseOrderDetailContract.Presenter

    private val orderItems = ArrayList<PurchaseOrderDetailBean.OrderItemsBean>()
    private var detailBean: PurchaseOrderDetailBean? = null

    private var mDialog: CustomDialog? = null
    private var mDialog2: CustomDialog2? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase_order_detail)
        ARouter.getInstance().inject(this)
        initView()
        addListener()
    }

    private fun initView() {
        showBackButton()
        setTitleText(R.string.order_detail)

        val manager = LinearLayoutManager(this@PurchaseOrderDetailActivity)
        manager.orientation = LinearLayoutManager.VERTICAL
        val paint = Paint()
        paint.strokeWidth = 30f
        paint.color = ContextCompat.getColor(this@PurchaseOrderDetailActivity, R.color.line_color)
        paint.isAntiAlias = true
        recycler_order.addItemDecoration(HorizontalDividerItemDecoration.Builder(this@PurchaseOrderDetailActivity).paint(paint).build())
        recycler_order.layoutManager = manager

        Timber.e("orderId=$orderId")

        mAdapter = PurchaseOrderDetailAdapter(R.layout.item_order_purchase_detail, orderItems)
        headerView = layoutInflater.inflate(R.layout.view_order_header, recycler_order.parent as ViewGroup, false)
        footerView = layoutInflater.inflate(R.layout.view_order_footer, recycler_order.parent as ViewGroup, false)
        headerView!!.text_receipt_info.visibility = View.GONE
        footerView!!.text_red_envelope_info.setOnClickListener {
            if (!TextUtils.isEmpty(couponId)) {
                ARouter.getInstance().build("/xy/coupon/detail")
                        .withString("couponId", couponId)
                        .withInt("type", 1)
                        .navigation()
            }
        }

        mAdapter.addHeaderView(headerView)
        mAdapter.addFooterView(footerView)
        recycler_order.adapter = mAdapter
    }

    override fun onResume() {
        super.onResume()
        mPresenter.takeView(this)
        mPresenter.loadOrderDetail(orderId)
    }

    private fun addListener() {
        btn_cancel_order.setOnClickListener {
            cancel(orderId)
        }

        btn_order_comment.setOnClickListener {
            comment(detailBean!!)
        }

        layout_order_payment.setOnClickListener {
            payment(orderId, detailBean!!.productAmountTotal)
        }

        btn_order_remind.setOnClickListener {
            remind(orderId)
        }

        btn_order_confirm_receipt.setOnClickListener {
            confirm(orderId)
        }

        btn_logistics.setOnClickListener {
            logistics(orderId)
        }

        btn_order_delete.setOnClickListener {
            delete(orderId)
        }

        btn_buy_again.setOnClickListener {
            buyAgain(orderId)
        }
    }

    private fun buyAgain(orderId: String) {
        ARouter.getInstance()
                .build("/xy/buy/again")
                .withString("orderId", orderId)
                .navigation()
    }

    private fun logistics(id: String) {
        mPresenter.orderLogistics(id)
    }

    private fun comment(listBean: PurchaseOrderDetailBean) {
        ARouter.getInstance()
                .build("/xy/order/evaluate")
                .withString("orderId", listBean.id)
                .navigation()
    }

    private fun payment(orderId: String, payMoney: BigDecimal) {
        ARouter.getInstance()
                .build("/xy/product/pay/dialog")
                .withString("orderId", orderId)
                .withObject("payMoney", payMoney)
                .withInt("type", 1)
                .navigation()
    }

    private fun delete(id: String) {
        mDialog = CustomDialog.Builder(this)
                .setMessage("是否删除")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                    mDialog!!.dismiss()

                    mPresenter.orderDelete(id)
                }.setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create()
        mDialog!!.show()
    }

    private fun cancel(id: String) {
        mDialog = CustomDialog.Builder(this)
                .setMessage("是否取消订单？")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                    mDialog!!.dismiss()

                    mPresenter.orderCancel(id)
                }.setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create()
        mDialog!!.show()
    }

    private fun remind(id: String) {
        mPresenter.remind(id)
    }

    private fun confirm(id: String) {
        mDialog = CustomDialog.Builder(this)
                .setMessage("请确认是否已经收到货物？")
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                    mDialog!!.dismiss()

                    mPresenter.confirm(id)
                }.setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create()
        mDialog!!.show()
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun loadOrderDetailSuccess(dataBean: PurchaseOrderDetailBean?) {
        progress_bar.visibility = View.GONE
        recycler_order.visibility = View.VISIBLE
        // 状态 0：未付款1：已付款,2：待发货 3:已发货 4：已完成 5：退货申请 6：退货中 7：已退货
        orderItems.clear()
        orderItems.addAll(dataBean!!.orderItems)
        mAdapter.setNewData(orderItems)
        mAdapter.loadMoreComplete()

        detailBean = dataBean
        couponId = dataBean.regPacketId
        if (!TextUtils.isEmpty(couponId)) {
            footerView!!.layout_red_envelope.visibility = View.VISIBLE
            if (null != dataBean.regPacketMoney) {
                val regPacketMoney = NumberFormatUtils.getInstance().format(dataBean.regPacketMoney.toDouble()) + "元"
                footerView!!.text_red_envelope_info.text = regPacketMoney
            }
        } else {
            footerView!!.layout_red_envelope.visibility = View.GONE
        }

        if (null != dataBean.orderAmountTotal) {
            val orderAmountTotal = "实付" + NumberFormatUtils.getInstance().format(dataBean.orderAmountTotal.toDouble())
            footerView!!.text_total_price.text = orderAmountTotal

            val orderTotal = "实付款:" + NumberFormatUtils.getInstance().format(dataBean.orderAmountTotal.toDouble())
            text_total.text = orderTotal
        }
        if (null != dataBean.productAmountTotal) {
            val productAmountTotal = "订单总价" + NumberFormatUtils.getInstance().format(dataBean.productAmountTotal.toDouble())
            footerView!!.text_payment.text = productAmountTotal
        }
        val addressBean = dataBean.address
        if (null != addressBean) {
            val province = addressBean.province
            val city = addressBean.city
            val district = addressBean.district
            val address = addressBean.address
            val detailAddress = province + city + district + address
            headerView!!.text_name.text = addressBean.contacts
            headerView!!.text_phone.text = addressBean.contactNumber
            headerView!!.text_address.text = detailAddress
        }
        when (dataBean.orderStatus) {
            0 -> {
                layout_bottom_tools.visibility = View.VISIBLE
                layout_order_payment.visibility = View.VISIBLE
                layout_order_payment.setBackgroundColor(ContextCompat.getColor(this, R.color.normal_text_color))
                btn_cancel_order.visibility = View.VISIBLE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.GONE
                btn_logistics.visibility = View.GONE
                btn_order_delete.visibility = View.GONE
                btn_buy_again.visibility = View.GONE
                btn_order_comment.visibility = View.GONE
                text_total.visibility = View.VISIBLE
                footerView!!.text_total_price.visibility = View.GONE

                val payTimeOut = dataBean.jzTime
                val now = dataBean.sysTime
                val distance = getDistanceTime(now, payTimeOut)
                countdown = Countdown(distance * 1000, 1000)
                countdown!!.start()
            }
            -1, 1 -> {
                layout_bottom_tools.visibility = View.VISIBLE
                layout_order_payment.visibility = View.GONE
                btn_cancel_order.visibility = View.GONE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.GONE
                btn_logistics.visibility = View.GONE
                btn_order_delete.visibility = View.VISIBLE
                btn_buy_again.visibility = View.GONE
                btn_order_comment.visibility = View.GONE
                text_total.visibility = View.GONE
                footerView!!.text_total_price.visibility = View.VISIBLE
            }
            2 -> {
                layout_bottom_tools.visibility = View.VISIBLE
                layout_order_payment.visibility = View.GONE
                btn_cancel_order.visibility = View.GONE
                btn_order_remind.visibility = View.VISIBLE
                btn_order_confirm_receipt.visibility = View.GONE
                btn_logistics.visibility = View.GONE
                btn_order_delete.visibility = View.GONE
                btn_buy_again.visibility = View.GONE
                btn_order_comment.visibility = View.GONE
                text_total.visibility = View.GONE
                footerView!!.text_total_price.visibility = View.VISIBLE
            }
            3 -> {
                layout_bottom_tools.visibility = View.VISIBLE
                layout_order_payment.visibility = View.GONE
                btn_cancel_order.visibility = View.GONE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.VISIBLE
                btn_logistics.visibility = View.VISIBLE
                btn_order_delete.visibility = View.GONE
                btn_buy_again.visibility = View.GONE
                btn_order_comment.visibility = View.GONE
                text_total.visibility = View.GONE
                footerView!!.text_total_price.visibility = View.VISIBLE
            }
            4 -> {
                layout_bottom_tools.visibility = View.VISIBLE
                layout_order_payment.visibility = View.GONE
                btn_cancel_order.visibility = View.GONE
                btn_order_remind.visibility = View.GONE
                btn_order_confirm_receipt.visibility = View.GONE
                btn_logistics.visibility = View.VISIBLE
                btn_order_delete.visibility = View.VISIBLE
                btn_buy_again.visibility = View.VISIBLE
                btn_order_comment.visibility = View.VISIBLE
                text_total.visibility = View.GONE
                footerView!!.text_total_price.visibility = View.VISIBLE
            }
            else -> {
                layout_bottom_tools.visibility = View.GONE
            }
        }
    }

    override fun loadOrderDetailFailure() {
        Timber.e("loadOrderDetailFailure")
        progress_bar.visibility = View.GONE
        layout_bottom_tools.visibility = View.GONE
        recycler_order.visibility = View.GONE
    }

    override fun orderCancelSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "取消订单成功")
        finish()
    }

    override fun orderCancelFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun orderDeleteSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "删除订单成功")
        finish()
    }

    override fun orderDeleteFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun orderRemindSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "操作成功！！！")
    }

    override fun orderRemindFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun orderConfirmSuccess(resp: BaseResp?) {
        ToastUtil.showTip(this, "操作成功！！！")
    }

    override fun orderConfirmFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun orderLogisticsSuccess(dataBean: LogisticsResp.DataBean?) {
        val title = dataBean!!.expressCompany + "  单号: " + dataBean.expressNo
        val deliveryTime = "发货时间: " + dataBean.deliveryTime
        mDialog2 = CustomDialog2.Builder(this)
                .setTitle(title)
                .setMessage(deliveryTime)
                .create()
        mDialog2!!.show()
    }

    override fun orderLogisticsFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
        Timber.tag("PurchaseOrderDetailActivity").e("orderLogisticsFailure")
    }

    internal inner class Countdown(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onFinish() {
            countdown!!.cancel()
            text_order_payment.text = "付款超时"
            layout_order_payment.setBackgroundColor(ContextCompat.getColor(this@PurchaseOrderDetailActivity, R.color.enable_background))
            text_countdown.visibility = View.GONE
            btn_cancel_order.visibility = View.GONE
        }

        override fun onTick(millisUntilFinished: Long) {
            text_countdown.text = toClock(millisUntilFinished)
        }
    }

    private fun toClock(millisUntilFinished: Long): String {
        var hour = millisUntilFinished / (60 * 60 * 1000)
        var minute = (millisUntilFinished - hour * 60 * 60 * 1000) / (60 * 1000)
        var second = (millisUntilFinished - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000
        if (second >= 60) {
            second = second % 60
            minute += second / 60
        }
        if (minute >= 60) {
            minute = minute % 60
            hour += minute / 60
        }
        var sh = ""
        var sm = ""
        var ss = ""
        if (hour < 10) {
            sh = "0" + hour.toString()
        } else {
            sh = hour.toString()
        }
        if (minute < 10) {
            sm = "0" + minute.toString()
        } else {
            sm = minute.toString()
        }
        if (second < 10) {
            ss = "0" + second.toString()
        } else {
            ss = second.toString()
        }
        return "倒计时: $sh:$sm:$ss"
    }

    private fun getDistanceTime(str1: String, str2: String): Long {
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val one: Date
        val two: Date
        var sec: Long = 0
        try {
            one = df.parse(str1)
            two = df.parse(str2)
            val time1 = one.time
            val time2 = two.time
            val diff = time2 - time1
            sec = diff / 1000
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return sec
    }

    override fun onDestroy() {
        super.onDestroy()
        mDialog2?.let {
            mDialog2!!.dismiss()
            mDialog2 = null
        }

        countdown?.let {
            countdown!!.cancel()
        }
    }
}
